<template>
  <div class="dept-page art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-show="searchVisible"
      v-model="formFilters"
      :items="formItems"
      :showExpand="true"
      @reset="handleReset"
      @search="handleSearch"
    />

    <ElCard
      class="art-table-card dept-container"
      shadow="never"
      :style="{ 'margin-top': searchVisible ? '12px' : '0' }"
    >
      <!-- 表格头部 -->
      <ArtTableHeader
        :showZebra="false"
        :loading="tableLoading"
        v-model:columns="columnChecks"
        v-model:showSearchBar="searchVisible"
        @refresh="handleRefresh"
        @search="handleSearchToggle"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton v-if="hasAuth('sys:dept:create')" type="primary" @click="handleAddDept">
              新增机构
            </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <ArtTable
        ref="tableRef"
        rowKey="id"
        :loading="tableLoading"
        :columns="columns"
        :data="tableData"
        :stripe="false"
        :resize-observer="{ disabled: true }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :indent="20"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <template #empty>
          <ElEmpty description="暂无数据" />
        </template>
      </ArtTable>
    </ElCard>

    <!-- 机构弹窗 -->
    <DeptDialog v-model:visible="dialogVisible" :editData="editData" @submit="handleSubmit" />
  </div>
</template>

<script setup lang="ts">
  import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
  import ArtTableHeader from '@/components/core/tables/art-table-header/index.vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import { useAuth } from '@/composables/useAuth'
  import { useTableColumns } from '@/composables/useTableColumns'
  import { createSmartDebounce } from '@/utils/table/tableUtils'
  import { ElButton, ElCard, ElEmpty, ElMessage, ElMessageBox } from 'element-plus'
  import { computed, h, onMounted, reactive, ref } from 'vue'
  import DeptDialog from './modules/dept-dialog.vue'

  // API导入
  import { createDept, deleteDept, getDeptTree, updateDept } from '@/api/system-manage'

  defineOptions({ name: 'DeptManagement' })

  const { hasAuth } = useAuth()

  // 状态管理
  const tableLoading = ref(false)
  const tableRef = ref<InstanceType<typeof ArtTable> | null>(null)
  const searchVisible = ref(true) // 搜索区域显示状态

  // 弹窗相关
  const dialogVisible = ref(false)
  const editData = ref<any>(null)
  const currentSelectedDept = ref<any>(null) // 当前选中的机构，用于新增时作为默认上级机构
  const selectedRows = ref<any[]>([]) // 存储表格选中的行数据

  // 搜索相关
  const initialSearchState = {
    name: '',
    code: ''
  }

  const formFilters = ref({ ...initialSearchState })
  const appliedFilters = reactive({ ...initialSearchState })

  const formItems = computed(() => [
    {
      label: '机构名称',
      key: 'name',
      type: 'input',
      props: { clearable: true }
    },
    {
      label: '机构编码',
      key: 'code',
      type: 'input',
      props: { clearable: true }
    }
  ])

  // 表格数据
  const tableData = ref<any[]>([])

  // 表格列配置 - 部门相关字段
  const { columnChecks, columns } = useTableColumns(() => [
    {
      type: 'selection',
      width: 50
    },
    {
      prop: 'name',
      label: '机构名称',
      minWidth: 120
    },
    {
      prop: 'code',
      label: '机构编码',
      minWidth: 120
    },
    {
      prop: 'level',
      label: '层级',
      minWidth: 80
    },
    {
      prop: 'sort',
      label: '排序',
      minWidth: 80
    },
    {
      prop: 'status',
      label: '状态',
      minWidth: 80,
      formatter: (row: any) => {
        return row.status === '1' ? '启用' : '禁用'
      }
    },
    {
      prop: 'createTime',
      label: '创建时间',
      minWidth: 150
    },
    {
      prop: 'operation',
      label: '操作',
      width: 150,
      align: 'right',
      formatter: (row: any) => {
        // 使用Vue渲染函数添加编辑和删除按钮
        return h(
          'div',
          { class: 'flex justify-end gap-2' },
          [
            hasAuth('sys:dept:update') &&
              h(
                ElButton,
                {
                  type: 'primary',
                  size: 'small',
                  onClick: () => handleEditDept(row)
                },
                { default: () => '编辑' }
              ),
            hasAuth('sys:dept:delete') &&
              h(
                ElButton,
                {
                  type: 'danger',
                  size: 'small',
                  onClick: () => handleDeleteDept(row)
                },
                { default: () => '删除' }
              )
          ].filter(Boolean)
        )
      }
    }
  ])

  // 勾选行变色功能已通过行内row-style函数实现

  // 事件处理
  const handleReset = () => {
    Object.assign(formFilters.value, { ...initialSearchState })
    Object.assign(appliedFilters, { ...initialSearchState })
    getTableData()
  }

  const handleSearch = () => {
    Object.assign(appliedFilters, { ...formFilters.value })
    getTableData()
  }

  const handleRefresh = () => {
    getTableData()
  }

  // 搜索按钮切换事件处理
  const handleSearchToggle = () => {
    // 搜索按钮点击时，searchVisible状态会自动通过v-model更新
    // 这里可以添加额外的逻辑，如果需要的话
  }

  // 获取表格数据 - 添加防抖处理
  const getTableData = createSmartDebounce(async () => {
    tableLoading.value = true
    getDeptTree()
      .then((response) => {
        tableData.value = response || []
      })
      .catch((error) => {
        console.error('获取机构列表失败:', error)
        ElMessage.error('获取机构列表失败')
      })
      .finally(() => {
        tableLoading.value = false
      })
  }, 300)

  // 新增机构
  const handleAddDept = () => {
    editData.value = null
    // 优先使用表格选中的行作为上级机构
    if (selectedRows.value && selectedRows.value.length > 0) {
      editData.value = { parentId: selectedRows.value[0].id }
    }
    // 如果没有选中行但有点击过的行，使用点击过的行作为上级机构
    else if (currentSelectedDept.value) {
      editData.value = { parentId: currentSelectedDept.value.id }
    }
    dialogVisible.value = true
  }

  // 编辑机构
  const handleEditDept = (data: any) => {
    editData.value = { ...data }
    dialogVisible.value = true
  }

  // 表格行点击事件 - 选中机构后新增时默认选中该机构为上级机构
  const handleRowClick = (row: any) => {
    // 存储当前选中的机构信息，用于新增时作为默认上级机构
    currentSelectedDept.value = row
  }

  // 删除机构
  const handleDeleteDept = async (data: any) => {
    try {
      await ElMessageBox.confirm('确定要删除该机构吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await deleteDept(data.id)
      ElMessage.success('删除成功')
      getTableData()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }

  // 提交表单
  const handleSubmit = async (formData: any) => {
    try {
      const isEdit = !!editData.value?.id

      if (isEdit) {
        await updateDept(formData.id, formData)
      } else {
        await createDept(formData)
      }

      ElMessage.success(`${isEdit ? '编辑' : '新增'}成功`)
      getTableData()
      dialogVisible.value = false
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败')
    }
  }

  // 选择框变化处理
  const handleSelectionChange = (rows: any[]) => {
    // 存储选中的行数据，用于新增机构时设置上级机构
    selectedRows.value = rows
  }

  // 生命周期
  onMounted(() => {
    getTableData()
  })
</script>

<style lang="scss" scoped>
  .dept-page {
    display: flex;
    flex-direction: column;
    height: 100%;
    transform: translateZ(0);
    will-change: transform;
    contain: layout;
  }

  .dept-container {
    flex: 1;
    overflow: hidden;
    transform: translateZ(0);
    will-change: transform;
    contain: layout;
  }

  :deep(.art-table) {
    transform: translateZ(0);
    will-change: transform;
    contain: layout style paint;
  }

  :deep(.art-table-container) {
    transform: translateZ(0);
    will-change: transform;
    contain: layout style paint;
  }

  /* 树形结构样式优化 */
  :deep(.el-table__row) {
    transition: background-color 0.2s ease;
  }

  /* 树形结构连接线样式 */
  :deep(.el-table__indent) {
    padding-left: 8px !important;
  }

  /* 优化折叠/展开图标样式 */
  :deep(.el-table__expand-icon) {
    padding: 4px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  :deep(.el-table__expand-icon:hover) {
    color: var(--el-primary-color);
  }

  :deep(.art-table-body) {
    transform: translateZ(0);
    will-change: transform;
    contain: layout style paint;
  }

  :deep(.art-table-header) {
    contain: layout;
  }

  :deep(.art-table-row) {
    contain: layout;
  }

  :deep(.art-table-cell) {
    contain: layout;
  }

  .current-dept {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    contain: layout;
  }

  // 移动端响应式优化
  @media (width <= 768px) {
    .dept-page {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }

    .dept-container {
      flex: 1;
      min-height: 0;
    }

    :deep(.art-search-bar) {
      margin-bottom: 0;
    }

    :deep(.art-table-card) {
      margin-top: 8px !important;
    }
  }
</style>
